﻿using Architecture.Api.Application.Commands.LoginCommand;
using Architecture.Domain.Services.Interface;
using Architecture.Domian.DTO;
using Architecture.Domian.Entity;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Architecture.Api.Controllers
{
    /// <summary>
    /// 登录API接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {

        private readonly IConfiguration _configuration;
        private readonly IMediator _mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="mediator"></param>
        public LoginController(IConfiguration configuration, IMediator mediator)
        {
            _configuration = configuration;
            _mediator = mediator;
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<CodeDto> Login(LoginCommand command)
        {

            var result = await _mediator.Send(command);

            if (result.UId != 0)
            {
                var toke = JwtNewString(result.UId.ToString());

                result.Token = toke;
            }
            return result;
        }

        private string JwtNewString(string uId)
        {
            //1.生成JWT
            //Header,选择签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            //Payload,存放用户信息
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uId),
                new Claim(ClaimTypes.Role,"董事长"),
                new Claim(ClaimTypes.UserData,"测试")
            };

            //Signature
            //取出私钥并utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(
                issuer: _configuration["Authentication:Issuer"],      //发布者
                audience: _configuration["Authentication:Audience"],  //接收者
                claims: claims,                                       //存放的用户信息
                notBefore: DateTime.UtcNow,                           //发布时间
                expires: DateTime.UtcNow.AddDays(1),                  //有效期设置时间
                signingCredentials                                    //数字签名
                );


            //生成token字符串
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);

            return TokenStr;
        }
    }
}
